public class Visitor extends Thread
{
    private static final long VISIT_INTERVAL = 2000L;
    private static final long VISIT_OFFSET = 1000L;

    public static int waitList = 0;
    public static int numVisitors = 0;

    public static Object waitRoom = new Object();
    public static Object exposition = new Object();

    private void handleSleep(long millis)
    {
        try {
            this.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void handleWait(Object lock)
    {
        try {
            lock.wait();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void run()
    {
        System.out.println(getId() + " wants to enter the museum");
        int nWaitList = 0;
        synchronized (waitRoom)
        {
            while (waitList >= 10)
                handleWait(waitRoom);
            nWaitList = ++waitList;
            if (waitList >= 10)
                waitRoom.notifyAll();
        }

        System.out.println("    " + getId() + " has entered the waitroom");

        System.out.println("    " + nWaitList + " people in the waitroom");
        synchronized (waitRoom)
        {
            while (waitList < 10)
                handleWait(waitRoom);
            numVisitors += 1;
            if (numVisitors == waitList)
                waitList = 0;
        }

        System.out.println("    " + getId() + " has entered the exposition");

        handleSleep(((long) Math.random()) * VISIT_INTERVAL + VISIT_OFFSET);
        synchronized (exposition)
        {
            numVisitors -= 1;
            if (numVisitors == 0)
                exposition.notifyAll();
        }

        System.out.println(getId() + " has left the museum");
    }
}
